package taskinstance;

import java.util.ArrayList;

import datatransfer.DataTransferInstance;

public class IntermediateTask extends Task {
  private String fileToBeTransmitString;

  public IntermediateTask(String source, String target, String fileName) {
    super(source, target, fileName, false, false);
    this.fileToBeTransmitString = fileName;
  }

  @Override
  public void run() {
    ArrayList<Task> completeArrayList = tm.getCompleteList();
    ArrayList<Task> runningArrayList = tm.getRunningList();
    
    this.dtf = new DataTransferInstance(fileToBeTransmitString, targetIp);

    while (!dtf.isComplete()) {
      while (!tm.isOnline(targetIp)) {
        try {
          Thread.sleep(2000);
        } catch (Exception e) {

        }
      }
      // now target is online, even may be off-line the following time
      tm.lockTargetIp(targetIp);
      isPending = false;

      dtf.start();
      while (!dtf.isComplete()) {
        try {
          Thread.sleep(1000);
          if (dtf.isError()) {
            tm.releaseTargetIp(targetIp);
            isPending = true;
            break;
          }
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }

      if (dtf.isComplete()) {
        tm.releaseTargetIp(targetIp);
        synchronized (runningArrayList) {
          runningArrayList.remove(this);
          completeArrayList.add(this);
          // TODO do database job
        }
      }
    }
  }
}
